import { ipcService } from '@renderer/services/ipcService'
import { ElMessage } from 'element-plus'
import { defineStore } from 'pinia'

interface AppConfig {
  dbPath?: string
  sdwebuiPath?: string
  url?: string
  apiKey?: string
  model?: string
  baseUrl?: string
  rate?: number
  scale?: number
  comfyuiPath?: string
  comfyuiWsPath?: string
  sdEngine?: string
  comfyuiModel?: string
  baiduUrl?: string
  appid?: string
  appkey?: string
  salt?: string
  from?: string
  to?: string
  outputPath?: string
  loraPath?: string
  cachePath? : string
  imagesPath?: string
  useNativeLoraLoader?: boolean
}

export const useConfigStore = defineStore('config', {
  state: () => ({
    config: {} as AppConfig,
    // 新增：维护图片版本映射
    imageVersions: {} as Record<string, number>
  }),
  actions: {
    // 加载配置
    async loadConfig() {
      try {
        // 定义默认配置
        const defaultConfig = {
          sdwebuiPath: 'http://127.0.0.1:7860/sdapi/',
          url: 'https://api.siliconflow.cn/v1/chat/completions',
          model: 'deepseek-ai/DeepSeek-V3',
          baseUrl: 'http://127.0.0.1:8188/',
          comfyuiPath: 'http://127.0.0.1:8188/',
          comfyuiWsPath: 'ws://127.0.0.1:8188/',
          rate: 0.8,
          scale: 0.4,
          sdEngine: 'comfyui',
          baiduUrl: 'https://fanyi-api.baidu.com/api/trans/vip/translate',
          appid: '',
          appkey: '',
          salt: 'kiki',
          from: 'en',
          to: 'zh',
          loraPath: 'E:\\AI\\SDWEBUI\\stable-diffusion-webui-master\\models\\Lora',
          cachePath: 'E:\\CivitaiCache\\',
          imagesPath: 'D:\\myBox\\images',
          useNativeLoraLoader: true,
        };

        // 使用 Object.assign 合并配置（后端配置会覆盖默认配置）
        this.config = defaultConfig;
      } catch (error) {
        console.error('加载配置失败:', error);
        // 可以在这里处理错误或设置默认值
      }
    },

    async delayLoadConfig() {
      try {
        // 从后端获取配置
        const res = await ipcService.getGlobalConfig();
        const backendConfig = res.success ? res.data:{}
        // 定义默认配置
        const defaultConfig = {
          sdwebuiPath: 'http://127.0.0.1:7860/sdapi/',
          url: 'https://api.siliconflow.cn/v1/chat/completions',
          model: 'deepseek-ai/DeepSeek-V3',
          baseUrl: 'http://127.0.0.1:8188/',
          comfyuiPath: 'http://127.0.0.1:8188/',
          comfyuiWsPath: 'ws://127.0.0.1:8188/',
          rate: 0.8,
          scale: 0.4,
          sdEngine: 'comfyui',
          baiduUrl: 'https://fanyi-api.baidu.com/api/trans/vip/translate',
          appid: '',
          appkey: '',
          salt: 'kiki',
          from: 'en',
          to: 'zh',
          loraPath: 'E:\\AI\\SDWEBUI\\stable-diffusion-webui-master\\models\\Lora',
          cachePath: 'E:\\CivitaiCache\\',
          imagesPath: 'D:\\myBox\\images',
          useNativeLoraLoader: true,
        };

        // 使用 Object.assign 合并配置（后端配置会覆盖默认配置）
        this.config = Object.assign({}, defaultConfig, backendConfig);
      } catch (error) {
        console.error('加载配置失败:', error);
        // 可以在这里处理错误或设置默认值
      }
    },

    // 新增：提取文件名的工具方法
    getFileNameFromUrl(fileUrl: string): string {
      if (!fileUrl) return '';
      const decodedUrl = decodeURIComponent(fileUrl);
      let path = decodedUrl;
      if (decodedUrl.startsWith('file://')) {
        path = decodedUrl.replace('file://', '');
        if (path.startsWith('/') && (path[1] === ':' || path[2] === ':')) {
          path = path.slice(1);
        }
      }
      const fileName = path.split(/[\\/]/).pop() || '';
      return decodeURIComponent(fileName);
    },

    comfyProxyImage(fileUrl: string) {
      if (!fileUrl || !fileUrl.startsWith('file://')) {
        return fileUrl; // 非本地路径直接返回
      }
      
      const comfyBaseUrl = window.location.origin;
      const encodedPath = encodeURIComponent(fileUrl);
      // 获取文件名
      const fileName = this.getFileNameFromUrl(fileUrl);
      
      // 检查版本映射，不存在则初始化为0
      if (!this.imageVersions[fileName]) {
        this.imageVersions[fileName] = 0;
      }
      
      // 获取当前版本号
      const version = this.imageVersions[fileName];
      
      // 添加版本参数
      return `${comfyBaseUrl}/command/get-image?path=${encodedPath}&v=${version}`;
    },

    // 新增：更新图片版本号的方法
    updateImageVersion(fileUrl: string) {
      const fileName = this.getFileNameFromUrl(fileUrl);
      if (fileName) {
        this.imageVersions[fileName] = (this.imageVersions[fileName] || 0) + 1;
      }
    },

    // 保存配置
    async saveConfig(newConfig: Partial<AppConfig>) {
      try {
        const mergedConfig = { ...this.config, ...newConfig }
        await ipcService.saveConfig(mergedConfig)
        this.config = mergedConfig
        ElMessage.success('保存配置成功')
        return true
      } catch (error) {
        console.error('保存配置失败:', error)
        return false
      }
    },

    async handleSelectDatabase() {
      try {
        const result = await window.electron.ipcRenderer.invoke('select-database')
        if (result.success) {
          // 刷新数据
          this.config.dbPath = result.path
          ElMessage.success(result.path)
        } else {
          ElMessage.error(JSON.stringify(result))
        }
      } catch (err) {
        ElMessage.error('数据库切换失败:' + JSON.stringify(err))
      }
    },

    async handleSelectOutputPath() {
      try {
        const result = await ipcService.selectFileFolder()
        if (result.success) {
          // 刷新数据
          this.config.outputPath = result.path
          ElMessage.success(result.path)
        } else {
          ElMessage.error(JSON.stringify(result))
        }
      } catch (err) {
        ElMessage.error('输出路径选择失败:' + JSON.stringify(err))
      }
    },

    async handleSelectLoraPath() {
      try {
        const result = await ipcService.selectFileFolder()
        if (result.success) {
          // 刷新数据
          this.config.loraPath = result.path
          ElMessage.success(result.path)
        } else {
          ElMessage.error(JSON.stringify(result))
        }
      } catch (err) {
        ElMessage.error('Lora路径选择失败:' + JSON.stringify(err))
      }
    },

    async handleSelectImagesPath(){
      try {
        const result = await ipcService.selectFileFolder()
        if (result.success) {
          // 刷新数据
          this.config.imagesPath = result.path
          ElMessage.success(result.path)
        } else {
          ElMessage.error(JSON.stringify(result))
        }
      } catch (err) {
        ElMessage.error('图片路径选择失败:' + JSON.stringify(err))
      }
    },


    // 更新单个配置项
    updateConfigItem<T extends keyof AppConfig>(key: T, value: AppConfig[T]) {
      this.config[key] = value
      // 自动保存
      this.saveConfig({ [key]: value })
    },

    async convertToWebpV2(input: string | File) {
      return new Promise((resolve, reject) => {
        const img = new Image();

        // 统一处理函数
        const processImage = () => {
          try {
            const canvas = document.createElement('canvas');
            const ctx = canvas.getContext('2d');

            canvas.width = Math.round(img.width * (this.config?.scale || 1));
            canvas.height = Math.round(img.height * (this.config?.scale || 1));

            ctx.imageSmoothingEnabled = true;
            ctx.imageSmoothingQuality = 'high';
            ctx.drawImage(img, 0, 0, canvas.width, canvas.height);

            const webpBase64 = canvas.toDataURL('image/webp', this.config?.rate || 0.8);
            resolve(webpBase64);
          } catch (error) {
            reject(error);
          }
        };

        // 自动识别输入类型
        if (typeof input === 'string' && input.startsWith('data:image/')) {
          // 直接处理 base64
          img.onload = processImage;
          img.onerror = (e) => reject(new Error('Base64 图片加载失败'));
          img.src = input;
        } else if (input instanceof File) {
          // 文件处理流程
          const reader = new FileReader();
          reader.onload = (e) => {
            img.onload = processImage;
            img.onerror = (e) => reject(new Error('图片文件加载失败'));
            img.src = e.target.result as string;
          };
          reader.onerror = (error) => reject(error);
          reader.readAsDataURL(input);
        } else {
          reject(new Error('不支持的输入类型，仅支持 File 或 base64 字符串'));
        }
      });
    }
  },
  getters: {
    baseUrl: (state) => state.config.baseUrl
  }
})